/*
 * Project: Sudoku Explainer
 * Copyright (C) 2006-2007 Nicolas Juillerat
 * 
 * Project: Sudoku Hint Engine for Android
 * Copyright (C) 2010-2013 Emanuel Moecklin
 * 
 * Available under the terms of the Lesser General Public License (LGPL)
 */
package com.onegravity.sudoku.solver.data;

import java.util.BitSet;
import java.util.Vector;

import com.onegravity.sudoku.solver.HintResource;
import com.onegravity.sudoku.solver.R;

/**
 * A block of a sudoku grid (3x3 for normal Sudokus or squiggly for jigsaw puzzles).
 */
public class Block extends Region {

	private static final long serialVersionUID = -4784341611914434824L;
	
	private Grid grid;
	private int blockCode;
	private BitSet rows = new BitSet();
	private BitSet columns = new BitSet();
	private Vector<CellPosition> positions = new Vector<CellPosition>();

    Block(Grid grid, int blockCode, byte[][] blockCodes) {
    	this.grid = grid;
    	this.blockCode = blockCode;
    	// compute this blocks positions and find the intersections with rows and columns (block can be squiggly)
    	for (int y=0; y<9; y++) {
        	for (int x=0; x<9; x++) {
        		if (blockCodes[x][y]==blockCode) {
        			positions.add(new CellPosition(x, y));
        			rows.set(y);
        			columns.set(x);
        		}
        	}
    	}
        initRegion();
    }

    public int getBlockCode() {
        return this.blockCode;
    }

    public boolean contains(CellPosition pos) {
    	return positions.contains(pos);
    }

    @Override
    public Cell getCell(int index) {
    	CellPosition pos = positions.elementAt(index);
        return grid.getCell(pos.getX(), pos.getY());
    }

    @Override
    public boolean crosses(Region other) {
        return (other instanceof Row) ? rows.get( ((Row)other).getRowNum() ) :
        	   (other instanceof Column) ? columns.get( ((Column)other).getColumnNum() ) :
        	   (other instanceof Block) ? (blockCode == ((Block)other).blockCode) :
               super.crosses(other);
    }

    @Override
    public String toString() {
    	return HintResource.getString(R.string.hint_region_block);
    }

    @Override
    public String toFullString() {
        return toString() + " " + (blockCode+1); //$NON-NLS-1$
    }

    @Override
    public boolean equals(Object obj) {
    	if (! (obj instanceof Block)) return false;
    	return blockCode == ((Block) obj).blockCode;
    }

	@Override
	public int compareTo(Region another) {
		if (another instanceof Row) return 1;
		if (another instanceof Column) return 1;
		if (another instanceof ExtraRegionExtended) return -1;
    	return blockCode < ((Block) another).blockCode ? -1 : 1;
	}

}